import { _type } from "../utils/index.js"

const objectToQuery = (shapeObj) => {
  let params = Object.keys(shapeObj).filter(t => !['shape'].includes(t) && ['string', 'number'].includes(_type(shapeObj[t]))).map(t => {
    return `${t}=${shapeObj[t]}`
  }).join("&")
  return params
}

// scheme://host:port/path?query#fragment
export const updateRoute = (t) => {
  if (t) {
    const state = {}
    let { content, title, name } = t
    let { shapes } = content
    let url = ''
    // 参数
    if (shapes.length >= 1) {
      let shapeObj = shapes[0]
      let query = objectToQuery(shapeObj)
      url += `?${query}`
    }
    // 路由
    url += '#' + name
    history.pushState(state, title, url)
  }
}


export const updateRouteFragment = (t) => {
  if (t) {
    const state = {}
    let { title, name } = t
    let url = ''
    url += '#' + name
    history.pushState(state, title, url)
  }
}

export const updateRouteQuery = (t) => {
  if (t) {
    const state = {}
    let { content, title } = t
    let { shapes } = content
    let url = ''
    if (shapes.length >= 1) {
      let shapeObj = shapes[0]
      let query = objectToQuery(shapeObj)
      url += `?${query}`
    }
    // url += '#' + name
    history.pushState(state, title, url)
  }
}


export const getRoute = () => {
  let hash = location.hash
  if (hash.indexOf("#") === 0) {
    return hash.substring(1)
  }
  return ""
}

export const resetRoute = () => {
  let { hash, origin } = location
  let url = `${origin}/${hash}`
  let state = {}
  let title = ""
  history.pushState(state, title, url)
  location.reload()
}

export const queryToObject = () => {
  const res = {};
  const search = location.search;
  const paramArr = new URLSearchParams(search);
  paramArr.forEach((val, key) => {
    res[key] = isNaN(+val) ? val : +val;
  })
  return res;
}
